package com.topisv.tms.web.work;

import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.EdiOrderService;
import com.topisv.tms.service.LogisticsCompanyService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.tools.DataTablesUtils;
import com.topisv.tms.utils.DateUtils;
import com.topisv.tms.utils.enums.StatusEnums;
import com.topisv.tms.web.report.FirstPageController;

@Controller
@RequestMapping(value = "/v2/jdExpress")
public class JdExpressController {
    
    private static final Logger logger = LoggerFactory.getLogger(FirstPageController.class);
    
    @Autowired
    private CustomersService customersService;
    
    @Autowired
    private LogisticsCompanyService logisticsCompanyService;
    
    @Autowired
    private AreaGroupService areaGroupService;
    
    @Autowired
    private EdiOrderService ediOrderService;
    
    /**
     * 导向京东单号管理页面
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "v2_init")
    public String toFirstPage(Model model, ServletRequest request) {
        
        //查出当前用户关联的商家列表
        ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
        List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
        model.addAttribute("customerList",customerList);
        
        //如果是商家用户,初始化数据
        if(StatusEnums.user_type_customer.getStatus().equals(curUser.userType)){
            String customerCode=customerList.get(0).getCustomerCode();
            model.addAttribute("customerCode", customerCode);
            //初始化仓库数据
            List<AreaGroup> warehouseList=this.areaGroupService.loadAreaGroupByAuthority(curUser,customerCode);
            model.addAttribute("warehouseList", warehouseList);
        }else if(StatusEnums.user_type_paiu.getStatus().equals(curUser.userType)){
            List<AreaGroup> warehouseList = areaGroupService.findByAreaGroups(curUser.areagroups);
            model.addAttribute("warehouseList", warehouseList);
        }
        return "work/jdExpress";
    }
    
    /**
     * 数据源—待处理订单
     * @param params
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value="/bindData_unhandle", method=RequestMethod.POST) 
    public void bindData_unhandle(@RequestBody JSONParam[] paramJson,HttpServletRequest request, HttpServletResponse response) throws Exception {
       try {
           //变量定义
           PrintWriter out=response.getWriter();
           JSONObject json=new JSONObject();
           Page<EdiOrder> page=null;
           
           //当前用户
           Map<String, Object> param=new HashMap<String, Object>();
           ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
           
           //客户端参数
           Map<String, String> paramMap = DataTablesUtils.convertToMap(paramJson);
           String sEcho = paramMap.get("sEcho");  
           int start = Integer.parseInt(paramMap.get("iDisplayStart"));
           int length = Integer.parseInt(paramMap.get("iDisplayLength")); 
           String customerCode = paramMap.get("customerCode");
           String warehouseCode = paramMap.get("warehouseCode");
           String dataRange = paramMap.get("dataRange");
           String cacode = "JD";
           //封装查询参数
           if(StringUtils.isEmpty(customerCode)){ //如果商家编码为空，赋予默认权限值
               String customerCodes=this.customersService.loadCustomerByAuthority(shiroUser.jobuuid);
               param.put("customerCodes", customerCodes);
           }else{
               param.put("customerCode", customerCode);
           }
           
           if(StringUtils.isEmpty(warehouseCode)){ //如果仓库编码为空，赋予默认权限值
               String areagroups=shiroUser.areagroups;
               param.put("areagroups", areagroups);
           }else{
               param.put("warehouseCode", warehouseCode);
           }
           
           if(StringUtils.isNotEmpty(dataRange)){
                Map<String, Date> dataMap=DateUtils.getDateRange(dataRange);
                Date fromDate=dataMap.get("fromDate");
                Date toDate=dataMap.get("toDate");
                param.put("fromDate", fromDate);
                param.put("toDate", toDate);
           }
         
           param.put("orderStatus", "ok");
           param.put("status", "pending");
           param.put("dispatchFlag", "1");
           
           param.put("companyCode", cacode);
           param.put("jdEmpty", "1");
           
           //查询
           int curPage=(start/length)+1;
           page = this.ediOrderService.loadPageOrder(param,curPage, length);
           List<EdiOrder> eOrderList=page.getContent();
           
           //封装查询结果
           json.put("aaData", eOrderList);
           json.put("sEcho", sEcho);
           json.put("iTotalRecords", page.getTotalElements());
           json.put("iTotalDisplayRecords", page.getTotalElements());
           
           out.print(json);
       
       } catch (Exception e) {
           
       }
   } 
    
    /**
     * 添加京东快递单号
     *
     * @param 
     * @return 
     * @throws 
     * @author Songlinhai
     * @version 1.0.0
     */
    @RequestMapping(value = "addExpressNo", method=RequestMethod.POST)
    public void addExpressNo(@RequestBody JSONParam[] jsonParam,ServletRequest request, ServletResponse response){
        PrintWriter out = null;
        JSONObject json = null;
        String msg = null;
        Map<String, String> paramMap= null;
        try{
           out = response.getWriter();
           json = new JSONObject();
           paramMap = DataTablesUtils.convertToMap(jsonParam);
           
           for(String key : paramMap.keySet()){
               System.out.println(key + " " + paramMap.get(key));
           }
           
           
       }catch(Exception e){
           logger.error("添加京东快递单号失败",e);
           json.put("content", "添加京东单号失败");
       }
        
         msg = ediOrderService.addExpressNoNew(paramMap);
        
        if(msg == ""){
            json.put("content", "成功");
        }else{
            json.put("content", msg);
        }
        
        out.print(json.toString());
        
        
    }
    
}
